package com.zjsystem.zjsy.controller;

import com.alibaba.excel.EasyExcel;
import com.google.common.collect.Lists;
import com.zjsystem.zjsy.result.Result;
import com.zjsystem.zjsy.utils.ExcelListener;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @Author: 王云飞
 * @name: UploadImgController
 * @Date: 2024/7/2 9:08
 */
@Slf4j
@RestController
@RequestMapping("admin")
public class UploadImgController {

    @Value("${filePath:}")
    private String string;

    @GetMapping("/fileSave")
    public Result fileSave(MultipartFile file, HttpServletRequest request) throws IOException {
        if (file.isEmpty()) {
            Result.fail().message("失败");
        }
        String oldName = file.getOriginalFilename();
        String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."), oldName.length());
        File folder = new File(string);
        if (!folder.isDirectory()) {
            folder.mkdirs();
        }

        file.transferTo(new File(folder, newName));
        log.info("文件保存成功： 存储路径{}, 名称{}", folder.getPath(), File.separator + newName);
        String filePath = request.getScheme() + "://" + request.getServerName() + ":"
                + request.getServerPort() + "/" + newName;
        return Result.ok(filePath);
    }

    @GetMapping("/readFile")
    public Result readFile(@RequestParam("name") String name) {
        String filePath = string + name;
        File file = new File(filePath);
        List<List<Object>> dataList = Lists.newArrayList();
        try {
            EasyExcel.read(filePath,new ExcelListener()).sheet().doRead();
            dataList = ExcelListener.getDataList();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        return Result.ok(dataList);
    }
}
